<template>
  <div class="menu-container">
    <el-row :gutter="20">
      <!-- 左侧树形菜单 -->
      <el-col :span="6">
        <el-card class="tree-card">
          <template #header>
            <div class="card-header">
              <span>菜单结构</span>
            </div>
          </template>
          <el-tree
              ref="menuTree"
              :data="menuTreeData"
              :expand-on-click-node="false"
              :highlight-current="true"
              :props="treeProps"
              class="menu-tree"
              node-key="id"
              @node-click="handleNodeClick"
          >
            <template #default="{ node, data }">
              <span class="custom-tree-node">
                <span>{{ node.label }}</span>
                <span class="node-actions">
                  <el-button size="small" text @click.stop="handleEdit(data)">
                    <el-icon><Edit/></el-icon>
                  </el-button>
                </span>
              </span>
            </template>
          </el-tree>
        </el-card>
      </el-col>

      <!-- 右侧详情 -->
      <el-col :span="18">
        <el-card class="detail-card">
          <template #header>
            <div class="card-header">
              <span>{{ currentMenu ? '菜单详情' : '请选择菜单' }}</span>
              <div v-if="currentMenu">
                <el-button
                    :icon="editMode ? 'View' : 'Edit'"
                    size="small"
                    type="primary"
                    @click="toggleEditMode"
                >
                  {{ editMode ? '查看模式' : '编辑模式' }}
                </el-button>
              </div>
            </div>
          </template>
          <div v-if="currentMenu">
            <div class="menu-edit">
              <el-form
                  ref="menuForm"
                  :model="currentMenu"
                  :rules="formRules"
                  label-width="120px"
              >
                <el-form-item label="菜单标题" prop="title">
                  <el-input v-model="currentMenu.title" :disabled="!editMode"/>
                </el-form-item>

                <!-- 关键修改：始终显示父菜单选择器（如果是子菜单） -->
                <el-form-item label="父级菜单" prop="parentId">
                  <el-popover
                      placement="bottom-start"
                      trigger="click"
                      width="300"
                  >
                    <template #reference>
                      <el-input
                          v-model="parentMenuName"
                          placeholder="请选择父级菜单"
                          readonly
                          :disabled="!editMode"
                      >
                      </el-input>
                    </template>
                    <div class="parent-tree-container">
                      <el-tree
                          ref="parentTree"
                          :data="parentMenuTreeData"
                          :expand-on-click-node="false"
                          :highlight-current="true"
                          :props="treeProps"
                          class="parent-tree"
                          node-key="id"
                          @node-click="handleParentNodeClick"
                      >
                        <template #default="{ node, data }">
                          <span class="custom-tree-node">
                            <span>{{ node.label }}</span>
                          </span>
                        </template>
                      </el-tree>
                    </div>
                  </el-popover>
                </el-form-item>

                <el-form-item label="路由" prop="router">
                  <el-input v-model="currentMenu.router" :disabled="!editMode"/>
                </el-form-item>

                <el-form-item label="组件路径" prop="componentPath">
                  <el-input v-model="currentMenu.componentPath" :disabled="!editMode"/>
                </el-form-item>

                <el-form-item label="排序" prop="orderNum">
                  <el-input-number
                      v-model="currentMenu.orderNum"
                      :disabled="!editMode"
                      :min="1"
                      controls-position="right"
                  />
                </el-form-item>

                <el-form-item label="是否显示" prop="active">
                  <el-switch v-model="currentMenu.active" :disabled="!editMode"/>
                </el-form-item>

                <el-form-item label="权限标识" prop="perms">
                  <el-input v-model="currentMenu.perms" :disabled="!editMode"/>
                </el-form-item>

                <el-form-item>
                  <el-button :disabled="!editMode" type="primary" @click="handleSave">保存</el-button>
                  <el-button :disabled="!editMode" @click="toggleEditMode">取消</el-button>
                </el-form-item>
              </el-form>
            </div>
          </div>
          <div v-else class="empty-tip">
            <el-empty description="请从左侧选择菜单查看详情"/>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script lang="ts" setup>
import {ref, onMounted, nextTick, computed} from 'vue'
import {type FormInstance, type FormRules} from 'element-plus'
import type {MenuItem, MenuTreeItem} from '@/type/menu'
import {message} from "@/utils/ElmessasgeUtils";
import {buildMenuTree} from "@/utils/routerUtils";
import {getMenuList, saveOrUpdate} from "@/api/system/menu";

const menuData = ref<MenuTreeItem>([])


async function updateMenuList() {
  let res: any = await getMenuList()
  if (res.data.code == 200) {
    menuData.value = res.data.data
  } else {
    message("获取菜单列表失败", 'error');
  }

}

// 树形配置
const treeProps = {
  label: 'title',
  children: 'children'
}

// 当前选中的菜单
const currentMenu = ref<MenuItem | null>(null)
const menuTree = ref()
const menuForm = ref<FormInstance>()

// 编辑模式
const editMode = ref(false)


// 父级菜单选择器相关
const parentTree = ref()
const parentMenuName = ref('')


// 表单验证规则
const formRules: FormRules = {
  title: [{required: true, message: '请输入菜单标题', trigger: 'blur'}],
  path: [{required: true, message: '请输入菜单路径', trigger: 'blur'}],
  menuType: [{required: true, message: '请选择菜单类型', trigger: 'change'}],
  orderNum: [{required: true, message: '请输入排序号', trigger: 'blur'}]
}


// 计算可选的父级菜单树（只能是目录类型）
const parentMenuTreeData = computed(() => {
  return buildMenuTree(menuData.value)
})

// 处理菜单数据为树形结构
const menuTreeData = computed(() => {
  return buildMenuTree(menuData.value)
})

// 节点点击事件
const handleNodeClick = (data: MenuItem) => {
  currentMenu.value = data

  // 设置父级菜单名称
  if (currentMenu.value.parentId) {
    const parent = menuData.value.find(item => item.id === currentMenu.value?.parentId)
    parentMenuName.value = parent?.title || ''
  } else {
    parentMenuName.value = ''
  }

  editMode.value = false
}

// 父级菜单节点点击事件
const handleParentNodeClick = (data: MenuItem) => {
  parentMenuName.value = data.title
}

// 切换编辑模式
const toggleEditMode = () => {
  if (editMode.value) {
    // 从编辑模式切换回查看模式
    editMode.value = false
  } else {
    // 从查看模式切换到编辑模式
    if (currentMenu.value) {
      // 设置父级菜单名称
      if (currentMenu.value.parentId) {
        const parent = menuData.value.find(item => item.id === currentMenu.value?.parentId)
        parentMenuName.value = parent?.title || ''
      } else {
        parentMenuName.value = ''
      }
      editMode.value = true
    }
  }
}

// 保存菜单
const handleSave = async () => {
  if (!menuForm.value) return
  try {
    const parent = menuData.value.find((item: any) => item.title === parentMenuName.value)
    const {children, ...dataWithoutChildren} = currentMenu.value;
    if (parent) {
      dataWithoutChildren.parentId = parent?.id
    }

    let res = await saveOrUpdate(dataWithoutChildren)
    if (res.data.code == 200) {
      message('保存成功')
      editMode.value = false
    } else {
      message('保存失败: ' + res.data.msg, 'error')
    }
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 编辑菜单
const handleEdit = (menu: MenuItem) => {
  currentMenu.value = menu
  // 设置父级菜单名称
  if (menu.parentId) {
    const parent = menuData.value.find(item => item.id === menu.parentId)
    parentMenuName.value = parent?.title || ''
  } else {
    parentMenuName.value = ''
  }
  editMode.value = true
}


// 初始化
onMounted(async () => {
  await updateMenuList();
  // 默认选中第一个节点
  if (menuTreeData.value.length > 0) {
    await nextTick(() => {
      menuTree.value?.setCurrentKey(menuTreeData.value[0].id)
      currentMenu.value = menuTreeData.value[0]
    })
  }
})
</script>

<style lang="scss" scoped>
.menu-container {
  padding: 20px;
  height: 100%;

  .tree-card, .detail-card {
    height: calc(100vh - 120px);
    overflow-y: auto;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .menu-tree {
    :deep(.el-tree-node__content) {
      height: 36px;
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      font-size: 14px;
      padding-right: 8px;

      .el-icon {
        margin-right: 8px;
        font-size: 16px;
      }

      .node-actions {
        margin-left: auto;
        display: flex;
        opacity: 0;
        transition: opacity 0.3s;
      }

      &:hover .node-actions {
        opacity: 1;
      }
    }
  }

  .menu-detail {
    padding: 10px;

    :deep(.el-descriptions__body) {
      background-color: #fafafa;
    }
  }

  .menu-edit {
    padding: 10px;

    .parent-tree-container {
      height: 300px;
      overflow-y: auto;

      .parent-tree {
        :deep(.el-tree-node__content) {
          height: 36px;
        }
      }
    }

    .icon-selector {
      display: flex;
      flex-wrap: wrap;
      max-height: 300px;
      overflow-y: auto;

      .icon-item {
        width: 100px;
        height: 60px;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        cursor: pointer;
        border-radius: 4px;
        margin: 4px;

        &:hover {
          background-color: #f5f7fa;
        }

        .el-icon {
          font-size: 24px;
          margin-bottom: 4px;
        }

        span {
          font-size: 12px;
          text-align: center;
          word-break: break-all;
        }
      }
    }
  }

  .empty-tip {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 300px;
  }
}
</style>